<template>
    <div class="app-container jklis">
         <div class="flex box">
      <div class="flex-l">
        <div class="titles">
          <img class="titles-left-img" src="@/assets/img/zidongfanxin-1.png" alt="">
        </div>
        <div class="tips">系统自动执行库存翻新 <span style="margin-left: 10px;"></span>   提升排名 加速出号</div>
       
        <el-button type="primary" size="small" @click="openAddTaskDialog" class="zdy-btn zdy-btn-rent">新增任务
          <img class="lines-img" src="@/assets/img/yunji-jiant.png" alt="">
        </el-button>
      </div>
      <div>
        <img class="titles-right-img" src="@/assets/img/zidongfanxin.png" alt="">
      </div>
    </div>
      
        <div class="zdy-main customTab">
            <el-tabs type="border-card" v-model="actived" @tab-click="tabChange" v-loading="loading">
                <el-tab-pane :label="tab.name" :name="tab.value" v-for="tab in statusList" :key="tab.value">
                    <div v-if="actived == 'task'"> 
                    <el-form :model="queryParams" ref="queryForm" :inline="true" class="zdy-form search-form-new"
                        label-width="68px" @keyup.enter.native="search">
                        <!-- <el-form-item label="部门" prop="deptIdList">
                            <el-select class="bumen" placeholder="部门筛选" multiple clearable>
                                <el-option v-for="dict in allDepts" :key="dict.deptId" :label="dict.deptName"
                                    :value="dict.deptId" />
                            </el-select>
                        </el-form-item> -->

                        <el-form-item label="店铺" prop="tenantId" v-if="userInfo.tenantId == 1">
                            <el-select class="bumen" placeholder="请选择店铺" filterable @change="dianpChange"
                                v-model="tenantId" clearable>
                                <el-option v-for="dict in shopList" :key="dict.tenantId" :label="dict.tenantName"
                                    :value="dict.tenantId" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="翻新渠道" prop="configId">
                            <el-select class="bumen" placeholder="翻新渠道" filterable @change="qudaoChange"
                                v-model="queryParams.configId" clearable>
                                <el-option v-for="(dict,index) in partnerList" :key="index" :label="dict.interName"
                                    :value="dict.id" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="翻新游戏" prop="gameId">
                            <el-select placeholder="翻新游戏" filterable clearable v-model="queryParams.gameIds">
                                <el-option v-for="dict in getGameLists" :key="dict.id" :label="dict.name"
                                    :value="dict.id"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="选择归属人" prop="channel" label-width="100px">
                            <el-select placeholder="请选择归属人" filterable clearable v-model="queryParams.userIds">
                                <el-option v-for="dict in allUsers" :key="dict.userId" :label="dict.nickName"
                                    :value="dict.userId"></el-option>
                            </el-select>

                        </el-form-item>
                        <el-form-item class="btns">
                            <el-button type="primary" icon="el-icon-search" size="mini" @click="searchList"
                                class="zdy-btn">搜索</el-button>
                            <el-button icon="el-icon-refresh" plain size="mini" @click="resetQuery"
                                class="zdy-btn zdy-btn-refresh">重置</el-button>
                        </el-form-item>
                    </el-form>
                    <div class="table_box table_box_new">
                        <el-table border  :data="tableData.records" style="width: 100%">
                            <el-table-column  label="渠道" prop="configName"></el-table-column>
                            <el-table-column  label="游戏" prop="gameNames"></el-table-column>
                            <el-table-column  label="频率(分钟)" prop="frequency"></el-table-column>
                            <el-table-column  label="时间段" prop="timePeriod" :formatter="formatTimePeriod">
                            </el-table-column>
                            <el-table-column  label="归属人" prop="userNames"></el-table-column>

                            <el-table-column  label="创建时间" prop="createTime"></el-table-column>
                            
                            <el-table-column label="任务状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      
                            <el-table-column  label="操作" width="150">
                                <template slot-scope="scope">
                                    <el-button type="text" @click="editTask(scope.row)">编辑</el-button>
                                    <el-button type="text" @click="deleteTask(scope.row)">删除</el-button>
                                    
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="pagination-container" v-if="tableData.total > 0">
                            <el-pagination background @size-change="handleSizeChange"
                                @current-change="handleCurrentChange" :current-page="queryParams.pageNum"
                                :page-sizes="[10, 20, 30, 50]" :page-size="queryParams.pageSize"
                                layout="total, sizes, prev, pager, next, jumper" :total="tableData.total">
                            </el-pagination>
                        </div>
                    </div>
                     </div>
                     <div v-if="actived == 'record'">
                         <el-form :model="recordForm" ref="recordForm" :inline="true" class="zdy-form search-form-new"
                         label-width="68px" @keyup.enter.native="search">
                           <el-form-item label="翻新任务" prop="renovateId">
                            <el-select class="bumen" placeholder="翻新任务" filterable 
                                v-model="recordForm.renovateId" clearable>
                                <el-option v-for="dict in recordTaskLists" :key="dict.id" :label="dict.configName"
                                    :value="dict.id" />
                            </el-select>
                        </el-form-item>
                             <el-form-item label="翻新渠道" prop="configId">
                            <el-select class="bumen" placeholder="翻新渠道" filterable @change="qudaoChange"
                                v-model="recordForm.configId" clearable>
                                <el-option v-for="(dict,index) in partnerList" :key="index" :label="dict.interName"
                                    :value="dict.id" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="翻新游戏" prop="gameId">
                            <el-select placeholder="翻新游戏" filterable clearable v-model="recordForm.gameIds">
                                <el-option v-for="dict in getGameLists" :key="dict.id" :label="dict.name"
                                    :value="dict.id"></el-option>
                            </el-select>
                        </el-form-item>
                          <el-form-item label="商品id" prop="goodsId">
                            <el-input placeholder="请输入商品id" v-model="recordForm.goodsId" clearable></el-input>
                        </el-form-item>
  <el-form-item label="下架状态" prop="downState">
                            <el-select placeholder="下架状态" filterable clearable v-model="recordForm.downState">
                                <el-option v-for="dict in downStateList" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                           <el-form-item label="上架状态" prop="upState">
                            <el-select placeholder="上架状态" filterable clearable v-model="recordForm.upState">
                                <el-option v-for="dict in upStateList" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>

                         
                         <el-form-item class="btns">
                            <el-button type="primary" icon="el-icon-search" size="mini" @click="getRenovationRecords"
                                class="zdy-btn">搜索</el-button>
                            <el-button icon="el-icon-refresh" plain size="mini" @click="resetRecordQuery"
                                class="zdy-btn zdy-btn-refresh">重置</el-button>
                        </el-form-item>
                        </el-form>
                          <div class="table_box table_box_new">
                        <el-table border  :data="recordTData" style="width: 100%">
                             <el-table-column  label="任务名称" prop="configName"></el-table-column>
                            <el-table-column  label="商品id" prop="goodsId"></el-table-column>
                            <el-table-column  label="游戏" prop="gameName"></el-table-column>
                            <el-table-column  label="下架状态" prop="downMsg">
                                <template slot-scope="scope">
                                    <span class="danger" v-if="scope.row.downState==2" type="danger">下架失败</span>
                                    <span class="success" v-else type="success">下架成功</span>
                                </template>
                            </el-table-column>
                             <el-table-column  label="上架状态" prop="upMsg">
                                <template slot-scope="scope">
                                    <span class="danger" v-if="scope.row.upState==2" type="danger">上架失败</span>
                                    <span class="success" v-else type="success">上架成功</span>
                                </template>
                            </el-table-column>
                            
                            <el-table-column  label="时间" prop="executeTime"></el-table-column>
                        </el-table>
                        <div class="pagination-container" v-if="recordTotal > 0">
                            <el-pagination background @size-change="handleSizeChangeTwo"
                                @current-change="handleCurrentChangeTwo" :current-page="recordForm.pageNum"
                                :page-sizes="[10, 20, 30, 50]" :page-size="recordForm.pageSize"
                                layout="total, sizes, prev, pager, next, jumper" :total="recordTotal">
                            </el-pagination>
                        </div>
                    </div>
                        

                     </div>
                </el-tab-pane>
            </el-tabs>
        </div>
        <!-- 新增任务弹窗 -->
        <el-dialog title="自动翻新" :visible.sync="dialogVisible" width="900px" :close-on-click-modal="false">
            <div class="task-dialog-content">
                <div class="task-info-section">
                    <div class="task-info-title">功能介绍：</div>
                    <div class="task-info-desc">
                        <p>* 自动翻新：通过自动化的定时上下架更新商品展示权重；</p>
                        <p>* 功能说明：系统读取您指定的【翻新渠道+游戏】，取最早一条对接数据进行定时翻新，直至您的任务删除；</p>
                        <p>* 付费标准：1个库存/1虞豆（举个例子："08:00～24:00全时段，预计一天消耗192虞豆（16*60/5*0.1），请保持充足的虞豆。</p>
                        <p>* 虞豆不足时任务状态会变为【暂停】，充值后需【手动】开启。</p>
                    </div>
                </div>
                <div class="task-setting-section">
                    <div class="task-setting-title">任务设置：</div>
                    <el-form :model="taskForm" :rules="rules" ref="taskForm" label-width="120px" class="task-form">
                        <el-form-item label="翻新渠道" prop="configId">
                            <el-select v-model="taskForm.configId" filterable placeholder="请选择翻新渠道" style="width: 94%"
                                @change="qudaoChange">
                                <el-option v-for="(partner,index) in partnerList" :key="index" :label="partner.interName"
                                    :value="partner.id"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="翻新游戏" prop="">
                            <el-select v-model="taskForm.gameIds" multiple placeholder="请选择翻新游戏" style="width: 94%" filterable
                                @change="gameChange">
                                <el-option v-for="game in gameList" :key="game.id" :label="game.name"
                                    :value="game.id"></el-option>
                            </el-select>
                            <el-tooltip class="item" effect="dark" content="选择需要翻新的游戏" placement="right">
                                <i class="el-icon-question help-icon"></i>
                            </el-tooltip>
                        </el-form-item>
                        <el-form-item label="翻新频率(分钟)" prop="frequency">
                            <el-input v-model="taskForm.frequency" placeholder="翻新频率（不低于5分钟）"
                                style="width: 94%"></el-input>
                            <el-tooltip class="item" effect="dark" content="设置翻新的时间间隔，最低5分钟" placement="right">
                                <i class="el-icon-question help-icon"></i>
                            </el-tooltip>
                        </el-form-item>
                        <el-form-item label="翻新时间段">
                            <div class="time-range-checkboxes">
                                <el-checkbox v-model="taskForm.timePeriod[0]">00:00～07:59</el-checkbox>
                                <el-checkbox v-model="taskForm.timePeriod[1]">08:00～15:59</el-checkbox>
                                <el-checkbox v-model="taskForm.timePeriod[2]">16:00～23:59</el-checkbox>
                            </div>
                            <el-tooltip class="item" effect="dark" content="选择翻新的时间段" placement="right">
                                <i class="el-icon-question help-icon"></i>
                            </el-tooltip>
                        </el-form-item>

                        <el-form-item label="翻新时间">
                            <el-date-picker v-model="timerange" type="daterange" range-separator="至"
                                start-placeholder="开始日期" value-format="yyyy-MM-dd" end-placeholder="结束日期">
                            </el-date-picker>
                        </el-form-item>

                        <el-form-item label="归属人">
                            <virtual-select @change="visibleChange" v-model="taskForm.userIds" :list="allUsers"
                                label="nickName" value="userId" :placeholder="'请选择归属人'" :keeps-params="20"
                                :is-concat="false" :concat-symbol="' || '" :is-multiple="true" :disabled="false"
                                :allow-create="false" />
                        </el-form-item>
                    </el-form>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" :loading="loading" @click="createTask">{{ editJobid?'修改任务':'创建任务'}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import gameListApi from "@/api/gameConfig/gameList";
import { shopList } from "@/api/system/shopManage";
import { listDept } from "@/api/system/dept";
import supplyConfigApi from "@/api/system/supplyConfig";

import { renovateList, jobList, addJob, editJob, editJobs , delJob ,getRenovateRecord , changeStatus} from "@/api/tool/gen";
import VirtualSelect from "@/components/VirtualSelect.vue";


export default {
    components: { VirtualSelect },

    data() {
        return {
            tableData: {
                records: [],
                total: 0
            },
            getGameLists:[],
            recordForm:{
                renovateId:'',
                configId:'',
                gameId:'',
                goodsId:'',
                downState:'',
                upState:'',
                pageSize: 10,
                pageNum: 1
            },
             recordTData:[],
             recordTotal:0,
            recordTaskLists:[],
            downStateList: [
                { label: "成功", value: "1" },
                { label: "失败", value: "2" },
            ],
            upStateList: [
                { label: "成功", value: "1" },
                { label: "失败", value: "2" },
            ],
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                configId: '',
                gameIds: '',
                userIds: '',

            },
            loading: false,
            actived: "task",
            dialogVisible: false, // 控制弹窗显示
            taskForm: {
                configId: '', // 翻新渠道
                gameIds: '', // 翻新游戏
                gameNames: '',
                frequency: '', // 翻新频率
                timePeriod: [false, false, false], // 翻新时间段 [00:00-07:59, 08:00-15:59, 16:00-23:59]
            },
            gameList: [],
            statusList: [
                {
                    name: "任务列表",
                    value: "task",
                },
                {
                    name: "翻新记录",
                    value: "record",
                },
            ],
            // allDepts: [],
            partnerList: [],
            allUsers: [], //所有用户列表
            timerange: [],
            taskGameList: [],
            shopList: [],
            editJobid: null,
            rules: {
                configId: [
                    { required: true, message: '请选择翻新渠道', trigger: 'change' }
                ],
                gameIds: [
                    { required: true, message: '请选择翻新游戏', trigger: 'change' }
                ],
                frequency: [
                    { required: true, message: '请输入翻新频率', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('请输入翻新频率'));
                            } else if (isNaN(value) || value <= 0) {
                                callback(new Error('翻新频率必须为正数'));
                            } else if (Number(value) < 5 ) {
                                callback(new Error('翻新频率不能低于5分钟'));
                            } else if ( Number(value)  > 59) {
                                callback(new Error('翻新频率不能大于等于60分钟'));
                            }
                            else {
                                callback();
                            }
                        },
                        trigger: 'blur'
                    }
                ]
            },
            tenantId:''
        }
    },
    computed: {
        userInfo() {
            return this.$store.getters.userInfo;
        },
    },
    created() {
        this.getAllGamList();
        if (this.userInfo.tenantId == 1) { // 代表是管理员
            this.getShopList()
        } else {
            this.queryParams.tenantId = this.userInfo.tenantId
        }
        this.renovateList()
        this.getTaskList();
        this.getAllUserList();


    },
    methods: {
           getAllGamList() {
      gameListApi.getGameList().then((res) => {
        this.getGameLists = res.rows;
      });
    },
        // 表格内时间段展示：将逗号分隔的小时字符串转为中文分段
        formatTimePeriod(row) {
            const val = row.timePeriod
            if (!val) return '-'
            // 收集到的小时集合
            const hours = String(val)
                .split(',')
                .map(h => h.trim())
                .filter(h => h !== '')
                .map(h => Number(h))
                .filter(h => !isNaN(h))

            if (hours.length === 0) return '-'

            const inRange = (start, end) => {
                for (let i = start; i <= end; i++) {
                    if (!hours.includes(i)) return false
                }
                return true
            }

            const parts = []
            if (inRange(0, 7)) parts.push('00:00～07:59')
            if (inRange(8, 15)) parts.push('08:00～15:59')
            if (inRange(16, 23)) parts.push('16:00～23:59')

            return parts.length ? parts.join('；') : '-'
        },
        async getShopList() {
            let data = {
                pageNum: 1,
                pageSize: 1000
            }
            const res = await shopList(data)
            this.shopList = res.rows
            this.queryParams.tenantId = ''
        },
        //获取翻新渠道
        async renovateList() {
            const res = await renovateList()
            try {
                this.partnerList = res.data
            } catch (error) {
                console.log(error)
            }
        },
        dianpChange(val) {
            console.log(val,77)
            this.queryParams.tenantId = val
            console.log(this.queryParams.tenantId)
        },
        qudaoChange(val) {
            //通过id 查询游戏
            this.getGameList(val)
        },
        getGameList(id) {
            // 根据选中的渠道ID查找对应的渠道数据
            const selectedPartner = this.partnerList.find(partner => partner.id === id);
            if (selectedPartner && selectedPartner.gameIds && selectedPartner.gameNames) {
                // 解析游戏ID和名称字符串
                const gameIds = selectedPartner.gameIds.split(',');
                const gameNames = selectedPartner.gameNames.split(',');
                // 创建游戏列表数据
                this.gameList = gameIds.map((gameId, index) => {
                    return {
                        id: gameId,
                        name: gameNames[index] || `游戏${gameId}` // 如果没有对应的名称，使用默认名称
                    };
                });
            } else {
                // 如果没有找到渠道数据或者没有游戏数据，清空游戏列表
                this.gameList = [];

                // this.$message.warning('该渠道没有可用的游戏数据');
            }
        },
        // 获取所有用户
        getAllUserList(val) {
            supplyConfigApi.getAllUserList({
                userNewType: 1
            }).then((res) => {
                this.allUsers = res.rows;
            });
        },        // 查询部门列表
        async getDeptList() {
            try {
                const { data } = await listDept()
                this.allDepts = data.filter(r => r.parentId != 100)
            } catch (error) {
            }
        },
        // 切换标签页
        tabChange(tab) {
            this.actived = tab.name;
            console.log(tab ,  this.actived);
            this.gameList = []
            if (this.actived === "task") {
                this.queryParams.pageSize = 10
                this.queryParams.pageNum = 1
                this.getTaskList();
            } else {
                this.recordForm.pageSize = 10
                this.recordForm.pageNum = 1
                this.getAllTaskList()
                this.getRenovationRecords();
            }
        },
        resetRecordQuery() {
            this.recordForm = {
                renovateId:'',
                configId:'',
                gameId:'',
                goodsId:'',
                downState:'',
                upState:'',
                pageSize: 10,
                pageNum: 1
            },
       
            this.getRenovationRecords();
        },
        searchList() {
            this.getTaskList()
        },
        visibleChange(val) {
              if(val.length == 0){
                this.taskForm.userIds = ''
              }
            // 支持单选和多选
            if (Array.isArray(val)) {
                const names = this.allUsers
                    .filter(user => val.includes(user.userId))
                    .map(user => user.nickName);
                this.taskForm.userNames = names.join(',');
            } else {
                const selectedUser = this.allUsers.find(user => String(user.userId) === String(val));
                this.taskForm.userNames = selectedUser ? selectedUser.nickName : '';
             
            }
        },
        resetQuery() {
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                configId: '',
                gameIds: '',
                userIds: ''
            };
            this.getTaskList();
            this.getTaskList();
        },
        //翻新记录获取所有的任务列表
            getAllTaskList() {
            let data = {
                pageNum: 1,
                pageSize: 1000,
            }
            jobList(data).then(res => {
                this.recordTaskLists = res.rows;
            })
        },
        // 获取任务列表
        getTaskList() {
            this.loading = true;
          
            jobList(this.queryParams).then(res => {
                this.tableData.records = res.rows;
                this.tableData.total = res.total;
            }).finally(() => {
                this.loading = false;
            });
        },
        gameChange(val) {
            // 根据选中的游戏ID获取游戏名称
            if (Array.isArray(val) && val.length > 0) {
                // 多选情况：获取所有选中游戏的名称
                const selectedGames = this.gameList.filter(game => val.includes(game.id));
                this.taskForm.gameNames = selectedGames.map(game => game.name).join(',');
            } else if (val && !Array.isArray(val)) {
                // 单选情况
                const selectedGame = this.gameList.find(game => game.id === val);
                this.taskForm.gameNames = selectedGame ? selectedGame.name : '';
            } else {
                // 没有选择游戏
                this.taskForm.gameNames = '';
            }
        },
        // 获取翻新记录
        getRenovationRecords() {
            this.loading = true;
            // 这里应该调用实际的API
            getRenovateRecord(this.recordForm).then(res=> {
                this.recordTData = res.rows
                this.recordTotal = res.total
            }).finally(() => {
                this.loading = false;
            });
        },
        handleSizeChangeTwo(val){
            this.recordForm.pageSize = val
            this.getRenovationRecords()
        },
        handleCurrentChangeTwo(val){
            this.recordForm.pageNum = val
            this.getRenovationRecords()
        },
        // 打开新增任务弹窗
        openAddTaskDialog() {
            this.dialogVisible = true;
            this.timerange = []
            this.editJobid = null
            // 重置表单
            this.taskForm = {
                configId: '', // 翻新渠道
                gameIds: '', // 翻新游戏
                frequency: '', // 翻新频率
                startDate: '',
                userNames: '',
                gameNames: '',
                endDate: '',
                timePeriod: [false, false, false], // 翻新时间段 [00:00-07:59, 08:00-15:59, 16:00-23:59]
                userIds: '' // 归属人
            };
        },
        // 创建任务
        createTask() {
            this.loading = true;
            this.$refs.taskForm.validate((valid) => {
                if (valid) {
                    // 处理时间段数据
                    const timePeriodData = this.getTimePeriodString();
                    if (this.timerange.length > 0) {
                        this.taskForm.startDate = this.timerange[0];
                        this.taskForm.endDate = this.timerange[1];
                    }
                    if (Array.isArray(this.taskForm.userIds) && this.taskForm.userIds.length > 0) {
                        this.taskForm.userIds = this.taskForm.userIds.join(',');
                    }
                    if (Array.isArray(this.taskForm.gameIds) && this.taskForm.gameIds.length > 0) {
                        this.taskForm.gameIds = this.taskForm.gameIds.join(',');
                    }else {
                        this.taskForm.gameIds = '';
                    }
                    const taskData = {
                        ...this.taskForm,
                        timePeriod: timePeriodData
                    };
                    console.log('时间段数据:', this.taskForm);
                    console.log('提交的任务数据:', taskData);
                    if (this.editJobid) { //代表是编辑
                        taskData.id = this.editJobid;
                        editJobs(taskData).then((res) => { 
                             if (res.code == 200) {
                                this.$message.success(res.msg);
                                this.dialogVisible = false;
                                this.getTaskList();
                            } else {
                                this.$message.error('创建任务失败');
                            }
                        });
                    } else {
                        addJob(taskData).then(res => {
                            if (res.code == 200) {
                                this.$message.success(res.msg);
                                this.dialogVisible = false;
                                this.getTaskList();
                            } else {
                                this.$message.error('创建任务失败');
                            }
                        })
                    }
                    this.loading = false;

                } else {
                    this.loading = false
                    return false;
                }
            });
        },

        // 获取时间段字符串
        getTimePeriodString() {
            const timeRanges = [];

            // 00:00～07:59 对应 0,1,2,3,4,5,6,7
            if (this.taskForm.timePeriod[0]) {
                timeRanges.push('0,1,2,3,4,5,6,7');
            }

            // 08:00～15:59 对应 8,9,10,11,12,13,14,15
            if (this.taskForm.timePeriod[1]) {
                timeRanges.push('8,9,10,11,12,13,14,15');
            }

            // 16:00～23:59 对应 16,17,18,19,20,21,22,23
            if (this.taskForm.timePeriod[2]) {
                timeRanges.push('16,17,18,19,20,21,22,23');
            }

            return timeRanges.join(',');
        },

        // 根据游戏ID数组设置游戏名称
        setGameNamesFromIds(gameIds) {
            if (Array.isArray(gameIds) && gameIds.length > 0) {
                const selectedGames = this.gameList.filter(game => gameIds.includes(game.id));
                this.taskForm.gameNames = selectedGames.map(game => game.name).join(',');
            } else {
                this.taskForm.gameNames = '';
            }
        },
        
        // 解析时间段字符串并设置复选框状态
        parseTimePeriodString(timePeriodStr) {
            if (!timePeriodStr) {
                this.taskForm.timePeriod = [false, false, false];
                return;
            }

            const hours = timePeriodStr.split(',').map(h => parseInt(h.trim()));

            // 重置时间段状态
            this.taskForm.timePeriod = [false, false, false];

            // 检查每个时间段是否包含在hours数组中
            // 00:00～07:59 (0-7)
            const period1Hours = [0, 1, 2, 3, 4, 5, 6, 7];
            if (period1Hours.every(h => hours.includes(h))) {
                this.taskForm.timePeriod[0] = true;
            }

            // 08:00～15:59 (8-15)
            const period2Hours = [8, 9, 10, 11, 12, 13, 14, 15];
            if (period2Hours.every(h => hours.includes(h))) {
                this.taskForm.timePeriod[1] = true;
            }

            // 16:00～23:59 (16-23)
            const period3Hours = [16, 17, 18, 19, 20, 21, 22, 23];
            if (period3Hours.every(h => hours.includes(h))) {
                this.taskForm.timePeriod[2] = true;
            }

            console.log(this.taskForm.timePeriod);
        },
        // 编辑任务
        editTask(row) {
            this.editJob(row.id)
            this.editJobid = row.id
            this.dialogVisible = true;
        },
        async editJob(id) {
            this.dialogVisible = true;
            const res = await editJob(id)
            const defaultTaskForm = {
                configId: '',
                gameIds: '',
                gameNames: '',
                frequency: '',
                startDate: '',
                endDate: '',
                userIds: '',
                userNames: '',
                timePeriod: [false, false, false]
            };
            const data = res.data || {};
            this.taskForm = Object.assign({}, defaultTaskForm, data);
            
            // 先设置渠道，获取游戏列表
            this.qudaoChange(this.taskForm.configId)
            
            // 处理游戏ID回显
            if (data.gameIds) {
                // 将逗号分隔的游戏ID字符串转为数组
                this.taskForm.gameIds = data.gameIds.split(',');
                // 根据游戏ID数组设置游戏名称
                this.setGameNamesFromIds(this.taskForm.gameIds);
            }
            
            if (data.userIds) {
                this.taskForm.userIds = data.userIds.split(',').map(Number);
            }

            // 处理时间段回显
            if (data.timePeriod) {
                this.parseTimePeriodString(data.timePeriod);
            } else {
                this.taskForm.timePeriod = [false, false, false];
            }
            // 处理日期范围回显
            if (data.startDate && data.endDate) {
                this.timerange = [data.startDate, data.endDate];
            }else {
                this.timerange = [];

            }
        },
        // 删除任务
        deleteTask(row) {
            this.$confirm('确认删除该任务吗? 删除后无法恢复', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                delJob(row.id).then(res=> {
                    this.$message.success(res.msg);
                     this.getTaskList();
                })
            }).catch(() => { });
        },

        // 处理每页显示数量变化
        handleSizeChange(val) {
            this.queryParams.pageSize = val;
            this.getTaskList();
        },

        // 处理页码变化
        handleCurrentChange(val) {
            this.queryParams.pageNum = val;
            this.getTaskList();
        },

        handleStatusChange(row) {
            let text = row.status === "0" ? "启用" : "暂停";
      this.$modal.confirm(`确认要任务${text}吗？`).then(function() {
        return changeStatus(row);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
        }
    }
}
</script>

<style lang="scss" scoped>
.header-actions {
    margin-bottom: 20px;
}

.task-dialog-content {
    padding: 0 20px;
}

.task-info-section {
    margin-bottom: 20px;
    background-color: #f8f9fa;
    padding: 15px;
    border-radius: 4px;
}

.task-info-title {
    font-weight: bold;
    margin-bottom: 10px;
}

.task-info-desc {
    color: #606266;
    line-height: 1.6;

    p {
        margin: 5px 0;
    }
}

.task-setting-section {
    margin-bottom: 20px;
}

.task-setting-title {
    font-weight: bold;
    margin-bottom: 15px;
}

.task-form {
    .el-form-item {
        margin-bottom: 22px;
    }
}

.time-range-checkboxes {
    display: inline-block;
    margin-right: 10px;

    .el-checkbox {
        margin-right: 20px;
    }
}

.help-icon {
    color: #909399;
    margin-left: 5px;
    cursor: pointer;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}

/* 表格内操作按钮间距 */
.el-button+.el-button {
    margin-left: 5px;
}

.danger {
color: rgb(225, 155, 43);
}

.success {
color: rgb(103, 189, 104);
}


.box {
  align-items: center;
  border-radius: 4px;
  padding: 10px 60px 20px;
  background: url('../../../../assets/img/yunji-bg.png') no-repeat;
  background-size: 100% 100%;
  margin-bottom: 10px;

  .flex-l {
    flex: 1;
  }

  .titles {
    color: rgba(51, 51, 51, 1);
    font-size: 18px;
  }

  .tips {
    color: #030C22;
    font-size: 24px;
    text-decoration-line: underline;
    margin: 0px 0 15px;
   
  }
}

.titles-left-img {
  width: 170px;
}

.titles-right-img {
  width: 200px;
}

.zdy-btn-rent {
  width: 120px;
  font-size: 16px;
  height: 40px;
}

.lines-img {
  margin-top: 2px;
  vertical-align: text-top;
  width: 18px;
  margin-left: 2px;
}
</style>
